package com.leyou.auth.service.impl;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.AuthService;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.PayLoad;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.privilege.client.ApplicationClient;
import com.leyou.privilege.dto.ApplicationDTO;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/14 0014
 * Time: 22:47
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {
    private static final String USER_ROLE = "role_user";
    private static final long redis_time = 5000;
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ApplicationClient applicationClient;

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            //查询用户
            UserDTO userDTO = userClient.queryUserByUserNameAndPassword(username, password);
            //生成UserInfo 无权限功能 暂时未guest
            UserInfo userInfo = new UserInfo(userDTO.getId(), username, USER_ROLE);
            //生成token
            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getUser().getExpire());
            //写入cookie
            CookieUtils.newBuilder()
                    //response 用于写cookie
                    .response(response)
                    // 保证安全防止xss跟攻击 不允许JS操作cookie
                    .httpOnly(true)
                    //设置domain leyou.com # cookie的域
                    .domain(jwtProperties.getUser().getCookieDomain())
                    // 设置cookie名称
                    .name(jwtProperties.getUser().getCookieName())
                    //值
                    .value(token)
                    //写成cookie
                    .build();
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
    }

    @Override
    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            //获取cookie中的token
            String token = CookieUtils.getCookieValue(request, jwtProperties.getUser().getCookieName());
            //获取userInfo
            PayLoad<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), UserInfo.class);
            // 获取token的Id 校验黑名单
            String id = payLoad.getId();
            // 判断是否存在  存在则无效
            Boolean aBoolean = redisTemplate.hasKey(id);
            if (aBoolean != null && aBoolean) {
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            //获取过期时间
            Date expiration = payLoad.getExpiration();
            //刷新过期时间  plusMinutes -返回此日期时间的副本减去指定的分钟数
            DateTime refreshTime = new DateTime(expiration.getTime()).minusMinutes(jwtProperties.getUser().getMinRefreshInterval());
            // 判断是否过了刷新的时间  isBefore:这一瞬间是在毫秒瞬间传入之前的
            if (refreshTime.isBefore(System.currentTimeMillis())) {
                //如果过了 则重新生成token
                token = JwtUtils.generateTokenExpireInMinutes(payLoad.getUserInfo(), jwtProperties.getPrivateKey(), jwtProperties.getUser().getExpire());
                //写入cookie
                CookieUtils.newBuilder()
                        //response 用于写cookie
                        .response(response)
                        // 保证安全防止xss跟攻击 不允许JS操作cookie
                        .httpOnly(true)
                        //设置domain leyou.com # cookie的域
                        .domain(jwtProperties.getUser().getCookieDomain())
                        // 设置cookie名称
                        .name(jwtProperties.getUser().getCookieName())
                        //值
                        .value(token)
                        //写成cookie
                        .build();
            }
            return payLoad.getUserInfo();
        } catch (Exception e) {
            log.error("用户验证信息失败", e);
            // 抛出异常，证明token无效，直接返回401
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }

    @Override
    public void logoutUser(HttpServletRequest request, HttpServletResponse response) {
        //获取cookie token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getUser().getCookieName());
        //解析token
        PayLoad<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), UserInfo.class);
        // 获取jwt的Id
        String id = payLoad.getId();
        // 获取有效的时长
        Date expiration = payLoad.getExpiration();
        //获取剩余时长
        long time = expiration.getTime() - System.currentTimeMillis();
        //剩余时间大于5s写入到redis
        if (time > redis_time) {
            redisTemplate.opsForValue().set(id, "", time, TimeUnit.MILLISECONDS);
        }
        // 删除cookie
        CookieUtils.deleteCookie(jwtProperties.getUser().getCookieName(), jwtProperties.getUser().getCookieDomain(), response);
    }

    @Override
    public String authenticate(Long id, String secret) {
        try {
            //查询 验证 Id和secret
            ApplicationDTO applicationDTO = applicationClient.queryApplicationByIdAndSecret(id, secret);
            //生成token
            AppInfo info = new AppInfo();
            info.setId(applicationDTO.getId());
            info.setServiceName(applicationDTO.getServiceName());
            return JwtUtils.generateTokenExpireInSeconds(info, jwtProperties.getPrivateKey(), jwtProperties.getPrivilege().getExpire());
        } catch (Exception e) {
            log.error("服务信息认证失败", e);
            throw new LyException(ExceptionEnum.APPLICATION_NOT_FOUND);
        }
    }
}
